<?php

namespace app\admin\model;

use app\common\model\Sms;
use app\model\CommonModel;
use think\facade\Db;
use think\model\concern\SoftDelete;

class SmsList extends CommonModel
{
    use SoftDelete;
    public function smsList($params)
    {
        $where = $this->setWhere($params);
        $paginate = [
               'page' => $params['page'] ?? 1,
               'list_rows' => $params['list_rows'] ?? 10,
           ];
        $attr = ['待发送', '已发送', '发送失败'];
        $list = self::where($where)
               ->order('id desc')
               ->paginate($paginate)->toArray();
        foreach ($list['data'] as &$nv) {
            $nv['status_text'] = $attr[$nv['status']];
            if (!empty($nv['send_at'])) {
                $nv['send_at'] = date('Y-m-d H:i:s', $nv['send_at']);
            } else {
                $nv['send_at'] = '';
            }
        }

        return success('操作成功', $list);
    }

    //设置条件
    public function setWhere($params)
    {
        $where = [];
        $createdDate = $params['sendDate'] ?? [];
        if (is_array($createdDate) && !empty($createdDate[0]) && $createdDate[1]) {
            $where[] = ['send_at', 'between time', [$createdDate[0], $createdDate[1].' 23:59:59']];
        }
        if (!empty($params['content'])) {
            $where[] = ['content', 'like', '%'.$params['content'].'%'];
        }
        if (isset($params['status']) && $params['status'] >= 0) {
            $where[] = ['status', '=', $params['status']];
        }

        return $where;
    }

    //添加短信通知
    public function addSms($params)
    {
        Db::startTrans();
        try {
            $date = date('Y-m-d H:i:s');
            $params['send_at'] = strtotime($params['send_at']);
            if (!empty($params['send_at'])) {
                if ($params['send_at'] < time()) {
                    return fail('更新失败：短信发送时间不能小于当前时间！');
                }
            } else {
                $params['send_at'] = 0;
            }
            //保存数据
            $id = $this->saveSms($params, $date);
            $saveAll = [];
            $saveSend['send_at'] = $params['send_at'];
            $saveSend['created_at'] = $date;
            $saveSend['sms_id'] = $id;
            $agent = $this->getAgent($params['ids']);
            foreach ($agent as $nk => $nv) {
                $saveSend['mobile'] = $nv['mobile'];
                $saveSend['agent_id'] = $nv['id'];
                $saveAll[] = $saveSend;
            }
            Db::name('sms_send_list')->insertAll($saveAll);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('更新失败：'.$e->getMessage());
        }

        return success('添加成功');
    }

    //保存sms
    public function saveSms($params, $date)
    {
        $save['content'] = $params['content'];
        $save['send_at'] = $params['send_at'];
        $save['send_num'] = count($params['ids']);
        $save['created_at'] = $date;
        $id = Db::name("sms_list")->insertGetId($save);

        return $id;
    }

    //显示代理商
    public function getAgent($ids)
    {
        $list = Db::name('agent')->where('id', 'in', $ids)->field('mobile,id')->select();

        return $list;
    }

    //删除短信通知
    public function delSms($params)
    {
        $result=self::destroy($params['id']);
        $sendList=SmsSendList::where("sms_id",$params['id'])->select();
         foreach ($sendList as $nk=>$nv){
               $nv->delete();
         }
        return success('删除成功');
    }

    //发送短信通知
    public function sendSms($params)
    {
        $id = $params['id'];
        $thisTime = time();
        $info = Db::name("sms_list")->where('id', $id)->find();
        $content = $info['content'];
        $list = Db::name('sms_send_list')->where('sms_id', $id)->where('status', 0)->select();
        $count = count($list);
        $mobile = [];
        if ($count > 0) {
            foreach ($list as $nk => $nv) {
                $mobile[] = $nv['mobile'];
            }
            $sendMobile = implode(',', $mobile);
            $sms = new Sms();
            $result = $sms->sendSms($sendMobile, $content);
            $result['respCode'] = 0;
            if ($result['respCode'] == 0) {
                $sendAt = $info['send_at'];
                if ($sendAt == 0) {
                    $sendAt = $thisTime;
                }
                Db::name('sms_send_list')->where('sms_id', $id)->update(['status' => 3, 'send_at' => $sendAt]);
                Db::name("sms_list")->where('id', $id)->update(['status' => 1, 'sending_num' => $info['send_num'], 'send_at' => $sendAt]);

                return success('发送成功！');
            } else {
                Db::name("sms_list")->where('id', $id)->update(['status' => 2, 'fail_msg' => $result['respMsg']]);

                return fail($result['respMsg']);
            }
        } else {
            return fail('发送失败！发送明细未找到待发送的手机号！');
        }
    }
}
